package net.vkits.anjiamiao.application;

import net.vkits.anjiamiao.domain.model.Device;
import net.vkits.anjiamiao.domain.repository.DeviceRepository;
import net.vkits.common.dto.DeviceDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Optional;

/**
 * Created by ethan-liu on 2016/11/24.
 */
@Service
public class DeviceApplicationService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceApplicationService.class);

    @Resource
    DeviceRepository deviceRepository;

    @Transactional
    public void addOrUpdateDevice(String cellphone, DeviceDTO deviceDTO) {
        Optional<Device> deviceOptional = deviceRepository.findByUmDeviceToken(deviceDTO.getUmDeviceToken());
        Device device = deviceOptional.orElse(new Device());
        device.setUmDeviceToken(deviceDTO.getUmDeviceToken());
        device.setAppInfo(deviceDTO.getAppInfo());
        device.setChannel(deviceDTO.getChannel());
        device.setLat(deviceDTO.getLat());
        device.setLng(deviceDTO.getLng());
        device.setMobileType(deviceDTO.getMobileType());
        device.setOs(deviceDTO.getOs());
        device.setResolution(deviceDTO.getResolution());
        device.setSysVersion(deviceDTO.getSysVersion());
        device.setCellphone(cellphone);
        device.setUpdateTime();
        deviceRepository.save(device);
    }

    public Page<Device> getDevice(Pageable pageable) {
        return deviceRepository.findAll(pageable);
    }
}
